# coding:utf-8
from django.conf import settings
from django.shortcuts import render
from django.http.response import JsonResponse
from django.utils.translation import gettext_lazy as _
from django.core.cache import cache
from app_admin.decorators import superuser_only,open_register
from app_admin.models import SysSetting
from loguru import logger
import json
import sys
import requests
import datetime

from app_admin.utils import decrypt_data
import requests
import json
from loguru import logger

class AIChatService:
    """AI聊天服务工具类"""
    def __init__(self, service_type='dify'):
        self.service_type = service_type
        self._load_config()
    
    def _load_config(self):
        """加载服务配置"""
        if self.service_type == 'dify':
            self.api_address = getattr(
                SysSetting.objects.filter(types='ai', name='ai_dify_api_address').first(),
                'value', ''
            )
            self.api_key = decrypt_data(getattr(
                SysSetting.objects.filter(types='ai', name='ai_dify_textgenerate_api_key').first(),
                'value', ''
            ))
            self.rate_limit = int(getattr(
                SysSetting.objects.filter(types='ai', name='ai_dify_textgenerate_rate_limit').first(),
                'value', 0
            ))
        else:
            raise ValueError(f"不支持的AI服务类型: {self.service_type}")

    def stream_chat(self, user_input, username):
        """流式聊天接口"""
        if not self.api_address or not self.api_key:
            logger.warning("AI服务配置不完整，跳过请求")
            yield json.dumps({'error': 'AI服务未配置'})
            return

        headers = {
            'Authorization': f'Bearer {self.api_key}',
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream'
        }

        try:
            with requests.post(
                f'{self.api_address.rstrip("/")}/chat-messages',
                headers=headers,
                data=json.dumps({
                    'inputs': '',
                    'query': user_input,
                    'response_mode': 'streaming',
                    'user': username
                }),
                stream=True
            ) as response:
                if response.status_code != 200:
                    logger.error(f"AI服务错误 - 状态码:{response.status_code} 响应:{response.text}")
                    yield json.dumps({'error': f'AI服务错误: {response.status_code}'})
                    return

                for chunk in response.iter_content(chunk_size=None):
                    if chunk:
                        yield chunk

        except Exception as e:
            logger.error(f"AI服务请求异常: {str(e)}")
            yield json.dumps({'error': str(e)})

# 获取系统配置
def get_sys_value(types, name, default=None):
    return getattr(SysSetting.objects.filter(types=types, name=name).first(), 'value', default)